package com.wechat.controller;

import com.wechat.entity.User;
import com.wechat.service.UserService;
import com.wechat.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody Map<String, String> body) {
        String username = body.get("username");
        String password = body.get("password");
        boolean success = userService.register(username, password);
        Map<String, Object> res = new HashMap<>();
        if (success) {
            res.put("msg", "注册成功");
        } else {
            res.put("msg", "用户名已存在");
        }
        return res;
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> body) {
        String username = body.get("username");
        String password = body.get("password");
        User user = userService.login(username, password);
        Map<String, Object> res = new HashMap<>();
        if (user != null) {
            String token = JwtUtil.generateToken(user.getId(), user.getUsername());
            res.put("id", user.getId());
            res.put("username", user.getUsername());
            res.put("token", token);
        } else {
            res.put("msg", "用户名或密码错误");
        }
        return res;
    }
}